package com.ansion.basetool.observer;

import android.text.TextUtils;

import androidx.annotation.Nullable;

import java.lang.ref.WeakReference;

/**
 * created by zhaoyuntao
 * on 27/04/2022
 * description:
 */
public class ObjectHolder<O> {
    String tag;
    private O o;
    private WeakReference<O> holder;

    private ObjectHolder() {
    }

    public ObjectHolder(@Nullable O o, @Nullable String tag, boolean weakReference) {
        this.tag = tag;
        if (weakReference) {
            holder = new WeakReference<>(o);
        } else {
            this.o = o;
        }
        if (TextUtils.isEmpty(this.tag) && o != null) {
            this.tag = String.valueOf(o.hashCode());
        }
    }

    public static <O> ObjectHolder<O> create() {
        return create(null);
    }

    public static <O> ObjectHolder<O> create(@Nullable O o) {
        return new ObjectHolder<>(o, null, false);
    }

    @Nullable
    public O getObject() {
        return holder != null ? holder.get() : o;
    }

    public void setObject(@Nullable O o) {
        if (holder != null) {
            holder = new WeakReference<>(o);
        } else {
            this.o = o;
        }
    }
}
